<template>
  <module>
    <div class="flex align-center justify-end" slot="page-actions">
      <el-button :loading="loading" @click="closePage(false)" size="mini" plain
        >返回</el-button
      >
      <el-button
        @click="resetForm"
        class="filter-item"
        size="mini"
        plain
        v-permission="['ADMIN', 'purchaseOrder-add']"
        >重置</el-button
      >
      <el-button
        @click="saveDraft"
        class="filter-item"
        type="primary"
        size="mini"
        v-permission="['ADMIN', 'purchaseOrder-add']"
        >保存草稿</el-button
      >
      <el-button
        :loading="loading"
        @click="saveForm(false)"
        size="mini"
        type="primary"
        >保存</el-button
      >
      <el-button
        @click="submitForm(true)"
        class="filter-item"
        size="mini"
        type="primary"
        v-permission="['ADMIN', 'purchaseOrder-submit']"
        >提交</el-button
      >
    </div>
    <div slot="page-content">
      <columnLayout
        :title="`采购单信息${
          fields.id ? `（单据编码:${fields.orderCode}）` : ''
        }`"
        border
      >
        <el-form
          :model="fields"
          :rules="rules"
          label-width="100px"
          ref="form"
          slot="content"
          v-loading="loading"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="所属供应商:" prop="supplierId">
                <el-select
                  :loading="loading"
                  clearable
                  filterable
                  placeholder="请选择所属供应商"
                  size="small"
                  v-model="fields.supplierId"
                >
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    v-for="item in supplierList"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟单员:" prop="merchandiser">
                <el-input
                  autocomplete="off"
                  maxlength="32"
                  placeholder="请输入跟单员"
                  size="small"
                  v-model.trim="fields.merchandiser"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购日期:" prop="purchaseDate">
                <el-date-picker
                  align="right"
                  placeholder="请选择采购日期"
                  size="small"
                  type="date"
                  v-model="fields.purchaseDate"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单金额¥:" prop="orderMoney">
                <el-input
                  autocomplete="off"
                  maxlength="32"
                  placeholder="请输入订单金额"
                  size="small"
                  v-model.trim="fields.orderMoney"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="备注:" prop="comment">
                <el-input
                  autocomplete="off"
                  maxlength="200"
                  placeholder="请输入备注"
                  rows="1"
                  show-word-limit
                  size="small"
                  type="textarea"
                  v-model="fields.comments"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col
              :span="6"
              v-if="fields.fileList && fields.fileList.length > 0"
            >
              <el-form-item label="附件信息:">
                <el-tag
                  style="cursor: pointer"
                  v-for="(tag, index) in fields.fileList"
                  :key="tag.id"
                  @click="showFile(tag.path)"
                  type="success"
                  closable
                  @close="removefile(index)"
                  effect="dark"
                  >{{ tag.name }}</el-tag
                >
              </el-form-item>
            </el-col>-->
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="上传附件:" prop="fileList">
                <upload-file action="/" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </columnLayout>
      <columnLayout title="采购明细列表">
        <el-button
          @click="onAddGoodsBtnClick()"
          class="filter-item"
          icon="el-icon-plus"
          size="mini"
          slot="column-actioons"
          type="primary"
          >定制产品</el-button
        >
        <el-button
          @click="showgoodsPage()"
          class="filter-item"
          icon="el-icon-plus"
          size="mini"
          slot="column-actioons"
          type="primary"
          >从产品库添加</el-button
        >
        <vxe-table
          :data="fields.detailList"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :loading="loading"
          align="left"
          border
          highlight-current-row
          ref="table"
          resizable
          show-header-overflow
          show-overflow
          size="mini"
          slot="content"
        >
          <vxe-table-column
            align="center"
            fixed="left"
            title="序号"
            type="seq"
            width="50px"
          />
          <vxe-table-column
            field="code"
            fixed="left"
            title="产品编码"
            width="100px"
          />
          <vxe-table-column
            field="name"
            fixed="left"
            title="产品名称"
            width="100px"
          />
          <vxe-table-column field="specs" title="产品规格" width="100px" />
          <vxe-table-column
            :edit-render="{
              placeholder: '请输入产品数量',
              name: '$input',
              props: { type: 'int' },
              maxlength: '11',
            }"
            align="right"
            field="number"
            title="产品数量"
          ></vxe-table-column>
          <vxe-table-column
            :edit-render="{
              placeholder: '请输入单价',
              name: '$input',
              props: { type: 'int', placeholder: '请输入单价' },
              maxlength: '11',
            }"
            align="right"
            field="price"
            title="产品单价￥"
          ></vxe-table-column>
          <vxe-table-column
            align="right"
            field="totalMoney"
            title="小计￥"
            width="100px"
          >
            <template v-slot="{ row }">{{
              row.totalMoney | moneyFormat
            }}</template>
          </vxe-table-column>
          <vxe-table-column field="unit" title="单位" width="100px" />
          <vxe-table-column
            align="right"
            field="taxRate"
            title="税率"
            width="100px"
          />
          <vxe-table-column
            align="right"
            field="taxMoney"
            title="税额￥"
            width="100px"
          >
            <template v-slot="{ row }">{{
              row.taxMoney | moneyFormat
            }}</template>
          </vxe-table-column>
          <vxe-table-column field="comment" title="备注" width="100px" />
          <vxe-table-column
            align="center"
            fixed="right"
            title="操作"
            width="100px"
          >
            <template slot-scope="scope">
              <vxe-button
                @click="deleteDetail(scope.$index, scope.row)"
                icon="el-icon-delete"
                size="mini"
                status="danger"
              ></vxe-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </columnLayout>
    </div>
    <!-- <goodsPage @addBomList="addBomList" v-if="goodsPage" v-model="goodsPage" /> -->
    <productSelect ref="productSelect" @closeDialog="closeDialog" />
    <!-- 新建产品组件 -->
    <goodsForm
      v-if="goodsForm"
      v-model="goodsForm"
      @colseDialog="colseDialog"
    />
  </module>
</template>

<script>
// import goodsPage from './goodsPage'
import productSelect from './productSelect.vue'
import goodsForm from './goodsForm.vue'
import module from '@/components/module'
import columnLayout from '@/components/columnLayout'
import uploadFile from '@/components/uploadFile'

export default {
  components: {
    // goodsPage,
    productSelect,
    goodsForm,
    module,
    columnLayout,
    uploadFile,
  },
  props: {
    value: {
      type: Object,
      default: () => Object.create({}),
    },
  },
  data() {
    return {
      loading: false,
      isShow: true,
      goodsPage: null,
      goodsForm: null,
      dialog: false,
      fileList: [
        {
          name: 'foodfoodfoodfoodfoodfoodfoodfoodfoodfoodfoodfood.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
        {
          name: 'food2.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
      ],
      fields: {
        comment: '',
        detailList: [
          {
            id: '1',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: '',
            price: 23.0,
            totalMoney: 46.0,
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
          {
            id: '2',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: 2,
            price: '',
            totalMoney: '46.00',
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
          {
            id: '3',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: '',
            price: 23.0,
            totalMoney: 46.0,
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
          {
            id: '4',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: 2,
            price: '',
            totalMoney: '46.00',
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
          {
            id: '5',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: '',
            price: 23.0,
            totalMoney: 46.0,
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
          {
            id: '6',
            name: '张三',
            code: 15029666666,
            specs: '',
            number: 2,
            price: '',
            totalMoney: '46.00',
            unit: '元',
            taxRate: '',
            taxMoney: '',
            comment: '',
          },
        ],
      },
      ifInvoiceList: [
        { label: '否', value: false },
        { label: '是', value: true },
      ],
      supplierList: [
        {
          seq: '1',
          name: '贵州成德钢铁有限公司',
          simpleName: '贵州钢铁',
          person: '张三',
          type: 's',
          phone: 15029666666,
          address: '北京默默地址',
          enabled: true,
          taxNo: '15784574SGDFS85',
          bankName: '中国工商银行一个支行',
          bankNo: 61525898565878547,
          code: '21-02-04',
          comment: '',
        },
        {
          id: '2',
          name: '上海宝钢钢铁有限公司',
          simpleName: '上海宝钢',
          person: '张三',
          type: 'sc',
          phone: 15029666666,
          address: '北京默默地址',
          enabled: true,
          taxNo: '15784574SGDFS85',
          bankName: '中国工商银行一个支行',
          bankNo: 61525898565878547,
          code: '21-02-04',
          comment: '备注信息',
        },
        {
          id: '3',
          name: '四川城建集团',
          simpleName: '四川城建',
          type: 'c',
          person: '张三',
          phone: 15029666666,
          address: '北京默默地址',
          enabled: true,
          taxNo: '15784574SGDFS85',
          bankName: '中国工商银行一个支行',
          bankNo: 61525898565878547,
          code: '21-02-04',
          comment: '',
        },
      ],
      unitTypeList: [
        { label: '计件', value: 'jj' },
        { label: '计重', value: 'jz' },
        { label: '计容', value: 'jr' },
      ],
      rules: {
        supplierId: [
          {
            required: true,
            message: '请选择所属供应商',
            trigger: 'blur',
          },
        ],
        merchandiser: [
          {
            required: true,
            message: '请输入跟单员',
            trigger: 'blur',
          },
        ],
        purchaseDate: [
          {
            required: true,
            message: '请选择采购日期',
            trigger: 'blur',
          },
        ],
      },
      title: '新增',
    }
  },
  watch: {
    isShow: function () {
      this.$emit('input', null)
    },
  },
  created() {
    if (!this.$route.query.data) {
      this.title = '新增'
      this.fields.detailList = []
      // this.initData()
    } else {
      this.title = '编辑'
      this.fields = this.$route.query.data
    }
  },
  computed: {},
  methods: {
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    initData() {
      for (let index = 0; index < 100; index++) {
        const item = {
          id: index,
          name: `张三${index + 1}`,
          code: new Date().getTime(),
          specs: '',
          number: '',
          price: 23.0,
          totalMoney: 46.0,
          unit: '元',
          taxRate: '',
          taxMoney: '',
          comment: '',
        }
        this.fields.detailList.push(item)
      }
    },
    onOkBtnClick(isSubmit) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (isSubmit) {
            this.$notify({
              title: '提交成功',
              type: 'success',
              duration: 1500,
            })
            this.loading = false
            this.$router.push({ path: '/purchase-order' })
          } else {
            this.$notify({
              title: '保存成功',
              type: 'success',
              duration: 1500,
            })
            this.loading = false
          }
        }
      })
    },
    deleteDetail(index, row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => this.fields.detailList.splice(index, 1))
    },
    removefile(index) {
      this.fields.fileList.splice(index, 1)
    },
    onAddGoodsBtnClick() {
      this.goodsForm = {}
      this.goodsForm.bomList = []
    },
    colseDialog() {
      this.goodsForm = null
    },
    showgoodsPage() {
      // this.goodsPage = {}
      const _this = this.$refs.productSelect
      _this.dialog = true
    },
    closeDialog() {
      const _this = this.$refs.productSelect
      _this.dialog = false
    },
    addBomList(row) {
      row.number = 0
      row.price = row.salesPrice
      row.totalMoney = '1000'
      this.fields.detailList.push(row)
    },
    /**
     * 关闭页面
     */
    closePage(closeFlag) {
      const _this = this
      if (!this.fields.id) {
        this.$confirm('是否保存当前数据？', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃保存直接返回',
          type: 'warning',
        })
          .then(() => {
            // if (closeFlag) {
            //   this.$store.dispatch('delView', { path: '/purchase-form' })
            // }
            console.log('要跳转了')
            _this.$router.push('/standard')
          })
          .catch(() => {
            // if (closeFlag) {
            //   this.$store.dispatch('delView', { path: '/purchase-form' })
            // }
            this.$router.push('/standard')
          })
      } else {
        // if (closeFlag) {
        //   this.$store.dispatch('delView', { path: '/purchase-form' })
        // }
        this.$router.push({ path: '/standard' })
      }
    },
    //

    //重置
    resetForm() {
      this.$confirm('确定要重置此页面吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.fields = {}
        this.$notify({
          type: 'success',
          message: '重置成功!',
        })
      })
    },
    //保存草稿
    saveDraft() {
      this.$notify({
        type: 'success',
        message: '保存成功!',
      })
    },
    //提交
    saveForm() {
      this.$notify({
        type: 'success',
        message: '保存成功!',
      })
    },
    //提交
    submitForm() {
      this.$confirm('确定要提交吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.fields = {}
        this.$notify({
          type: 'success',
          message: '提交成功!',
        })
      })
    },
  },
}
</script>

<style scoped></style>
